import Vue from 'vue'
import VueRouter from 'vue-router'
// 进度条
import NProgress from 'nprogress'
Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: () => import('@/views/login.vue')
  },
  {
    path: '/',
    redirect: '/welcome',
    component: () => import('@/views/Home.vue'),
    children: [
      {
        path: '/welcome',
        component: () => import('@/views/welcome.vue')
      },
      // 用户
      {
        path: '/users',
        component: () => import('@/views/users/users.vue')
      },
      // 权限
      {
        path: '/roles',
        component: () => import('@/views/roles/roles.vue')
      },
      {
        path: '/rights',
        component: () => import('@/views/roles/rights.vue')
      },
      // 商品
      {
        path: '/goods',
        component: () => import('@/views/goods/goods.vue')
      },
      {
        path: '/goods/add',
        component: () => import('@/views/goods/components/add.vue')
      },
      {
        path: '/params',
        component: () => import('@/views/goods/params.vue')
      },
      {
        path: '/categories',
        component: () => import('@/views/goods/categories.vue')
      },
      // 订单
      {
        path: '/orders',
        component: () => import('@/views/orders/orders.vue')
      },
      // 报道
      {
        path: '/reports',
        component: () => import('@/views/reports/reports.vue')
      }

    ]
  }

]

const router = new VueRouter({
  routes
})
// 路由守卫
router.beforeEach((to, from, next) => {
  // 进度条开始
  NProgress.start()
  // 拿到本地的token值
  const token = localStorage.getItem('token')
  // 如果有token
  if (token) {
    // 又想去登录页
    if (to.path === '/login') {
      // 去欢迎页
      next('/welcome')
      NProgress.done()
      // 有token不去登录页
    } else {
      // 放行
      next()
    }
    // 没有token
  } else {
    // 想去其他不用token就能去的页面
    if (to.path === '/login') {
      // 放行
      next()
    } else {
      // 回登录页
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
export default router
